#!usr/bin/perl 
use strict;
die "usage:perl $0 <muscle.list> <all.nuc.fa> <pep.list>\n" unless @ARGV == 3;
open C,$ARGV[0];open B,$ARGV[1];	open OUTN,">orth.gene.nuc.clw.list";	open D,$ARGV[2];
my %seq;my %h;  my %each;	my %tar;	my %geneid;
while(<D>){
	chomp;my @a=split;	open IN,$a[1];
	$/=">";<IN>;
	while(my $inf=<IN>){
		chomp $inf;my @b=split /\n+/,$inf;	my @c=split /\s+/,$b[0];
		$geneid{$c[0]}=$a[0];
	}
	close IN;
	$/="\n";
}
close D;
while(<C>){
	chomp;my @b=split;
	open A,$b[1];  $/=">";  <A>;
	while(my $inf=<A>){
		chomp $inf;my @a=split /\n+/,$inf; my $seq=join "",@a[1..$#a];
		$each{$b[0]}{$a[0]}=$seq;
	}
	close A;
	$/="\n";
}
close C;
#open OUTT,">Ortholog.gene.blast.align.txt";
$/=">";<B>;
while(my $inf=<B>){
	chomp $inf;my @a=split /\n+/,$inf;my @c=split /\s+/,$a[0];
	my $seq=join "",@a[1..$#a];		my $mod=int(length($seq)/3);
	for(my $i=0;$i <=$mod;$i++){
		$seq{$c[0]}[$i]=substr($seq,3*$i,3);
	}
}
close IN;
$/="\n";
`mkdir coregene_nuc`;
my $pwd=`pwd`;	chomp $pwd;
foreach my $k1(keys %each){
	open OUT2,">coregene_nuc/$k1.nuc.clw.fa";	print OUTN "$pwd/coregene_nuc/$k1.nuc.clw.fa\n";
	open OUT3,">coregene_nuc/$k1.nuc.clw.axt";
	print OUT3 ">$k1\n";
	foreach my $k2(sort keys %{$each{$k1}}){
		my $len=length $each{$k1}{$k2};
		my @base=split //,$each{$k1}{$k2};
		my $rec=0;
		print OUT2 ">$geneid{$k2}\n";        
		#print "$k1\t$h{$k1}\t@{$seq{$k1}}\n";
		foreach my $k(0..$#base){
			next if($base[$k] eq "*");
			if($base[$k] eq "-"){
				print OUT2 "---";	print OUT3 "---";	my $ddd="---";
				$tar{$geneid{$k2}}.=$ddd;
			}
			else{
				print OUT2 "$seq{$k2}[$rec]";	print OUT3 "$seq{$k2}[$rec]";
				$tar{$geneid{$k2}}.=$seq{$k2}[$rec];
				$rec++;
			}
		}
		print OUT2 "\n";	print OUT3 "\n";
	}
	close OUT2;	close OUT3;
}
close OUTN;
open OUT,">all.orth.gene.nuc.fa";
foreach my $k1(sort keys %tar){
	print OUT ">$k1\n$tar{$k1}\n";
}
close OUT;
